<template>
    <div class="content">
      <n-button type="info" @click="downloadCsv">导出CSV文件</n-button>
      <!-- 筛选框部分 -->
    <div class="filters" style="margin-top: 20px;">
      <n-select
        v-model:value="selectedTime"
        :options="TimeOptions"
        placeholder="筛选时间"
        style="width: 200px;"
        clearable="true"
      />
      <n-input placeholder="订单编号" style="width: 300px; margin-left: 20px" v-model:value="query"></n-input>
      <n-button type="info" @click="fetchOrderList">查询</n-button>
    </div>
      <n-spin :show="loading" size="large">
        <n-data-table
          ref="tableRef" 
          :columns="columns"
          :data="orderList"
          :pagination="paginationReactive"
          :bordered="true"
          :scroll-x="true"
          :row-key="rowKey"
          striped
          style="margin-top: 40px; max-height: 800px;" 
          :get-csv-cell="getCsvCell"
          :get-csv-header="getCsvHeader"
        />
      </n-spin>
    </div>
  </template>
  
  <script setup>
  import { onMounted, reactive, ref, h } from 'vue';
  import { NButton, NDataTable, NSpin, NCard,NSelect,NInput } from 'naive-ui';
  import axiosInstance from '@/utils/axios';
  import AMapLoader from '@amap/amap-jsapi-loader';
  
  const tableRef = ref(null); // 用于获取表格的ref
  const maps = reactive(new Map()); // 使用Map存储每个行的地图实例
  const columns = createColumns({});
  const selectedTime = ref(null);
  const query = ref(null);
  const TimeOptions = [
    { label: "近三天内", value: '3d' },
    { label: "近一周内", value: '1w' },
    { label: "近一月内", value: '1m' },
  ];
  const rowKey = (row) => row.record_id;
  
  // 生成唯一的containerId
  const generateContainerId = (machineId) => {
    return `container-${machineId}`;
  };
  
  // 初始化地图函数，展示路径和标注起点、终点
  const initMap = (id, trajectory, containerId) => {
    AMapLoader.load({
      key: "1cfd3a771aaf9dd11aa95a7472644c7e",  // API Key
      version: "2.0",  // 地图版本
      plugins: [], // 如果需要插件，可以在这里引入
    }).then((AMap) => {
      const map = new AMap.Map(containerId, {
        viewMode: "2D",   // 2D模式
        zoom: 12,         // 缩放级别
        center: trajectory[0],  // 初始中心位置，设置为轨迹的第一个点
      });
  
      // 使用轨迹数据绘制路径
      const path = trajectory.map(point => new AMap.LngLat(point[0], point[1]));
      const polyline = new AMap.Polyline({
        path: path,
        strokeColor: "#0091FF", // 轨迹颜色
        strokeWeight: 6, // 轨迹宽度
        strokeOpacity: 0.7, // 轨迹透明度
      });
  
      map.add(polyline);  // 将轨迹添加到地图上
  
      // 添加起点标记
      const startMarker = new AMap.Marker({
        position: path[0], // 轨迹的第一个点
        title: "起点",
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", // 蓝色标记
      });
      map.add(startMarker);
  
      // 添加终点标记
      const endMarker = new AMap.Marker({
        position: path[path.length - 1], // 轨迹的最后一个点
        title: "终点",
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png", // 红色标记
      });
      map.add(endMarker);
  
      // 创建右上角信息框
      const infoContainer = document.createElement('div');
      infoContainer.style.position = 'absolute';
      infoContainer.style.top = '10px';
      infoContainer.style.right = '10px';
      infoContainer.style.backgroundColor = 'white';
      infoContainer.style.padding = '10px';
      infoContainer.style.borderRadius = '8px';
      infoContainer.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.1)';
      infoContainer.innerHTML = `
        <div style="display: flex; align-items: center; margin-bottom: 8px;">
          <img src="https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png" style="width: 18px; height: 18px; margin-right: 8px;" alt="起点" />
          <span style="color: #0091FF; font-weight: bold;">起点</span>
        </div>
        <div style="display: flex; align-items: center;">
          <img src="https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png" style="width: 18px; height: 18px; margin-right: 8px;" alt="终点" />
          <span style="color: #f44336; font-weight: bold;">终点</span>
        </div>
      `;
  
      // 将信息框添加到地图的 DOM 上
      map.getContainer().appendChild(infoContainer);
  
      // 将地图实例存储在maps中
      maps.set(containerId, map);
    }).catch((error) => {
      console.error("AMap SDK 加载失败:", error);
    });
  };
  
  // 表格列定义
  function createColumns() {
    return [
      {
        type: "expand",
        renderExpand: (rowData) => {
          const containerId = generateContainerId(rowData.machine_id); // 为当前行生成唯一ID
          initMap(rowData.machine_id, rowData.tracejectory, containerId); // 初始化地图并绘制轨迹
          return h(NCard, { id: containerId, style: { width: '100%', height: '300px' } }, h('div', {}));  // 渲染地图容器
        }
      },
      {
        title: '创建时间',
        key: 'create_time',
        width: 100,
        ellipsis: { tooltip: true },
      },
      {
        title: '更新时间',
        key: 'update_time',
        width: 100,
        ellipsis: { tooltip: true },
      },
      {
        title: '订单编号',
        key: 'record_id',
        width: 100,
        ellipsis: { tooltip: true },
      },
      {
        title: '车辆编号',
        key: 'machine_id',
        width: 100,
        ellipsis: { tooltip: true },
      },
      {
        title: '开始骑行的时间',
        key: 'start_time'
      },
      {
        title: '结束骑行的时间',
        key: 'end_time'
      },
      {
        title: '停止时间',
        key: 'stop_time'
      },
      {
        title: '消耗的电量',
        key: 'consume_battery'
      },
      {
        title: '骑行人',
        key: 'username'
      },
    ];
  }
  
  // 表格数据（使用reactive）和分页配置
  const orderList = reactive([]);
  const maxpage = ref(0);
  const loading = ref(false);
  
  const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [3, 5, 10],
    onChange(page) {
      loading.value = true;
      if (page > paginationReactive.page && page > maxpage.value) {
        paginationReactive.page = page;
        fetchOrderList(page, paginationReactive.pageSize);
      } else {
        paginationReactive.page = page;
        loading.value = false;
      }
    },
    onUpdatePageSize(pageSize) {
      paginationReactive.pageSize = pageSize;
      paginationReactive.page = 1;
    },
  });
  
  // 获取订单列表数据
  const fetchOrderList = async () => {
    try {
      loading.value = true;
      const data = {
      'page':1,
      'page_size':500
    }
    // 如果有选择天数
    if (selectedTime.value !== null) {
      data.time_range = selectedTime.value;
    }

    // 如果有输入订单编号，加入 record_id 参数  
    if (query.value) {
      data.record_id = query.value;
    }
      const response = await axiosInstance.post('/api/get_record_list', data);
      if (response.data.success) {
        orderList.length = 0
        orderList.push(...response.data.data);
        maxpage.value = Math.ceil(response.data.total / paginationReactive.pageSize);
      } else {
        console.error('没有区域数据');
      }
    } catch (error) {
      console.error('请求失败', error);
    } finally {
      loading.value = false;
    }
  };
  
  onMounted(() => {
    fetchOrderList();
  });
  
  // 导出CSV的函数
  const downloadCsv = () => {
    // 获取列定义
    const columnsForCsv = columns.map(col => ({
      title: col.title,
      key: col.key,
    }));
  
  
    tableRef.value?.downloadCsv({
      fileName: "order-list",
      columns: columnsForCsv
    });
  };
  </script>
  
  <style scoped>
  .content {
    margin-left: 60px;
    margin-top: 20px;
    height: 1000px;
    width: 1130px;
  }
  .filters {
  display: flex;          
  gap: 20px;             
  margin-bottom: 20px;    
  }
  </style>
  